2023/12/23513字符

贪心算法

商店老板有1、2、5、10面额的纸币,小伙买东西给了100花了80,计算如何找零是最佳(阿里面试题)

function MinCoinChange(coins) {
  return function(amount) {
    let total = 0, change = [];
    for(let i= coins.length; i>=0; i--) {
      let coin = coins[i];
      while(total + coin <= amount) {
        change.push(coin);
        total += coin;
      }
    }
    return change;
  }
}

MinCoinChange([1,2,5,10])(20);  //--> 10, 10